import { authMiddleware } from '@/lib/api';
import { queryPath, queryPostNewInfo } from '@/services/api';
import { cookies } from 'next/headers';
import Metadata from '@/lib/metadata';
import ResetPage from '@/app/[locale]/reset/reset';
import type { Metadata as MetadataNext } from 'next';
import { createError, customException, getMetadata } from '@/lib/tool';
import type { IPath, IPostNewInfo } from '@/interfaces';
import EditPage from '@/app/[locale]/posts/[id]/edit/edit/editPage';
import Box from '@/app/[locale]/common/box/box';
import { getTranslator } from 'next-intl/server';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = await getTranslator(locale);
  return getMetadata({ title: t('postEditPage.createPost') });
}

export default async function Page({
  params: { locale },
  searchParams = {},
}: {
  params: { locale: string };
  searchParams: { v?: 'h5' };
}) {
  try {
    const t = await getTranslator(locale);
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = queryPostNewInfo({
      baseURL: process.env.APP_API_SERVER,
      token,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    const path = resp1.data as IPath;
    const info = resp2.data as IPostNewInfo;
    if (!path.user) {
      return (
        <ResetPage
          error={createError(
            customException(401, t('clientPage.unauthorizedValue')),
          )}
        />
      );
    }

    const metadata = new Metadata();
    metadata.set('page', ['/paths', '/posts/new'], path);
    metadata.set('newPost', ['/forum', '/posts', '/new'], info);

    return (
      <Box v={searchParams.v}>
        <EditPage
          source={info}
          translatedFields={{
            namePlaceholder: t('postEditPage.editPage.namePlaceholder'),
            contentPlaceholder: t('postEditPage.editPage.contentPlaceholder'),
            preview: t('postEditPage.editPage.preview'),
            cancelPreview: t('postEditPage.editPage.cancelPreview'),
            save: t('postEditPage.editPage.save'),
            editorDoesNotExist: t('postEditPage.editPage.editorDoesNotExist'),
            failedToInitializeEditor: t(
              'postEditPage.editPage.failedToInitializeEditor',
            ),
            saveCompleted: t('postEditPage.editPage.saveCompleted'),
            saveCompletedAboutToJump: t(
              'postEditPage.editPage.saveCompletedAboutToJump',
            ),
            titleRequired: t('postEditPage.editPage.titleRequired'),
            sectionIdRequired: t('postEditPage.editPage.sectionIdRequired'),
          }}
          editorTranslatedFields={{
            fileManager: t('postEditPage.editorDynamicPage.fileManager'),
          }}
          fileManagerTranslatedFields={{
            startUpload: t('postEditPage.fileManagerPage.startUpload'),
            selectFilePlaceholder: t(
              'postEditPage.fileManagerPage.selectFilePlaceholder',
            ),
            select: t('postEditPage.fileManagerPage.select'),
            delete: t('postEditPage.fileManagerPage.delete'),
            deleteCompleted: t('postEditPage.fileManagerPage.deleteCompleted'),
            selectFileToDelete: t(
              'postEditPage.fileManagerPage.selectFileToDelete',
            ),
            uploadCompleted: t('postEditPage.fileManagerPage.uploadCompleted'),
            fileDoesNotExist: t(
              'postEditPage.fileManagerPage.fileDoesNotExist',
            ),
          }}
        />
      </Box>
    );
  } catch (e) {
    return <ResetPage error={createError(e)} />;
  }
}
